<template>
  <div class="bg-plus">
    <div id="main" ref="echarts" />
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getWorkbenListAPI } from '@/apis/workben'
export default {
  data() {
    return {
      dataTotal: {
        annualIncomeArray: []
      },
      echartDate: [],
      myChart: null
    }
  },
  created() {
    this.getWorkbenList()
  },
  beforeDestroy() {
    if (this.myChart) {
      this.myChart.dispose()
    }
  },
  methods: {
    async getWorkbenList() {
      const res = await getWorkbenListAPI()
      // console.log(res.data.annualIncomeArray)
      this.dataTotal = res.data
      this.drawnEcharts(res.data)
    },
    // 柱形图
    drawnEcharts(data) {
      // console.log('绘制图表信息数据', data)
      // 检查是否已经存在 ECharts 实例
      if (!this.myChart) {
        this.myChart = echarts.init(this.$refs.echarts)
      } else {
        // 如果实例已存在，则清除之前的图表
        this.myChart.clear()
      }
      var option
      var series = [
        {
          data: data.annualIncomeArray.ybuilding,
          type: 'bar',
          stack: 'a',
          name: '物业费',
          barWidth: '25%'
        },
        {
          data: data.annualIncomeArray.yparking,
          type: 'bar',
          stack: 'a',
          name: '行车收入',
          barWidth: '25%'
        }
      ]
      const stackInfo = {}
      for (let i = 0; i < series[0].data.length; ++i) {
        for (let j = 0; j < series.length; ++j) {
          const stackName = series[j].stack
          if (!stackName) {
            continue
          }
          if (!stackInfo[stackName]) {
            stackInfo[stackName] = {
              stackStart: [],
              stackEnd: []
            }
          }
          const info = stackInfo[stackName]
          const data = series[j].data[i]
          if (data && data !== '-') {
            if (info.stackStart[i] == null) {
              info.stackStart[i] = j
            }
            info.stackEnd[i] = j
          }
        }
      }
      for (let i = 0; i < series.length; ++i) {
        const data = series[i].data
        for (let j = 0; j < series[i].data.length; ++j) {
          data[j] = {
            value: data[j]
          }
        }
      }
      option = {
        color: ['#3656ff', '#def4fc'],
        title: {
          text: '年度收入统计',
          textStyle: {
            fontSize: 14
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          right: 0,
          orient: 'vertical',
          itemWidth: 25,
          itemHeight: 12
        },
        xAxis: {
          type: 'category',
          data: data.annualIncomeArray.xmonth
        },
        yAxis: {
          type: 'value'
        },
        series: series
      }

      // 设置新的配置项并渲染图表
      this.myChart.setOption(option)
    }
  }
}
</script>

<style>
#main{
  height: 300px;
}
</style>
